/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.file.system.monitor;

import com.inspur.edp.lcm.metadata.api.entity.FileType;
import com.inspur.edp.lcm.metadata.api.service.FileAltMonitor;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class FileAltMonitorImpl implements FileAltMonitor {
    private String path;        // 文件夹目录

    private String fileSuffix;    // 需要监听的文件名后缀

    private long interval;        // 监听间隔

    private FileAlterationMonitor monitor; // 监视器

    private static final long DEFAULT_INTERVAL = 5 * 1000; // 默认监听间隔10s

    private boolean running = false;

    private FileAlterationListenerAdaptor listener;    // 事件处理类对象

    public FileAltMonitorImpl(String path, String fileSuffix, FileAlterationListenerAdaptor listenerAdaptor) {
        this(path, fileSuffix, DEFAULT_INTERVAL, listenerAdaptor);
    }

    public FileAltMonitorImpl(String path, FileAlterationListenerAdaptor listenerAdaptor) {
        this(path, DEFAULT_INTERVAL, listenerAdaptor);
    }

    public FileAltMonitorImpl(String path, long interval, FileAlterationListenerAdaptor listenerAdaptor) {
        this(path, "", interval, listenerAdaptor);
    }

    public FileAltMonitorImpl(String path, String fileSuffix, long interval,
        FileAlterationListenerAdaptor listenerAdaptor) {
        this.path = path;
        this.fileSuffix = fileSuffix;
        this.interval = interval;
        this.listener = listenerAdaptor;
        init();
    }

    public FileAltMonitorImpl(String path, FileType fileType, FileAlterationListenerAdaptor listenerAdaptor) {
        this(path, fileType, DEFAULT_INTERVAL, listenerAdaptor);
    }

    public FileAltMonitorImpl(String path, FileType fileType, long interval,
        FileAlterationListenerAdaptor listenerAdaptor) {
        this(path, parseToString(fileType), interval, listenerAdaptor);
    }

    private static String parseToString(FileType fileType) {
        switch (fileType) {
            case MDPKG:
                return ".mdpkg";
            case JAR:
                return ".jar";
            default:
                return null;
        }
    }

    private void init() {
        if (path == null || "".equals(path)) {
            throw new IllegalStateException("Listen path must not be null");
        }
        if (listener == null) {
            throw new IllegalStateException("Listener must not be null");
        }

        // 设定观察者，监听文件
        FileAlterationObserver observer;
        if (fileSuffix == null || "".equals(fileSuffix)) {
            observer = new FileAlterationObserver(path);
        } else {
            observer = new FileAlterationObserver(path,
                FileFilterUtils.suffixFileFilter(fileSuffix));
        }

        // 给观察者添加监听事件
        observer.addListener(listener);

        // FileAlterationMonitor本身实现了 Runnable，是单独的一个线程，按照设定的时间间隔运行，默认间隔是 10s
        monitor = FileAltMonitorFactory.create(interval);

        monitor.addObserver(observer);
    }

    /***
     * 开启监听
     */
    public void start() {
        try {
            monitor.start();
            running = true;
        } catch (Exception e) {
            throw new RuntimeException("monitor start error", e);
        }
    }

    public void stop() {
        try {
            monitor.stop();
            running = false;
        } catch (Exception e) {
            throw new RuntimeException("monitor stop error", e);
        }
    }

    public void checkAndNotify() {
        if (running) {
            for (FileAlterationObserver observer : this.monitor.getObservers()) {
                observer.checkAndNotify();
            }
        }
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setFileSuffix(String fileSuffix) {
        this.fileSuffix = fileSuffix;
    }

    public void setAdaptor(FileAlterationListenerAdaptor listenerAdaptor) {
        this.listener = listenerAdaptor;
    }
}
